<!DOCTYPE html>

<head>
    <meta charset="UTF-8">
    <style>
        html,
        body,
        #map {
            height: 100%;
        }

        .form-inline {
            display: inline;
        }

        #coordinateBox {
            width: 500px;
            height: 200px;
            overflow: auto;
            background: #00f6;
            color: #fff;
            position: absolute;
            z-index: 333;
        }

        #popup {
            height: 200px;
            width: 200px;
            margin-top: -200px;
            color: #fff;
            background: #253444b8;
        }

        #popup-closer {
            color: #fff;
        }
    </style>
    <title>一个最简单的例子</title>
    <link rel="stylesheet" href="../library/ol/ol.css">
    <link rel="stylesheet" href="../css/common.css">
    <script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.js"></script>
</head>

<body>
    <form class="form-inline">
        <label>Geometry type &nbsp;</label>
        <select id="type">
            <option value="Point">Point</option>
            <option value="LineString">LineString</option>
            <option value="Polygon">Polygon</option>
            <option value="Circle">Circle</option>
            <option value="None">None</option>
        </select>
        <select id="projection">
            <option value="EPSG:3857">EPSG:3857</option>
            <option value="EPSG:4326">EPSG:4326</option>
        </select>
    </form>
    <button id="toggle">TOGGLE BOX</button>
    <div id="coordinateBox">
        <span> </span> <br>
        输入名称：<input id="name" type="text"> <br>
        输入简介：<textarea id="describe" type="text"> </textarea>
        <button id="submit"> 保存 </button>
    </div>
    <div id="popup" class="ol-popup">
        <a href="#" id="popup-closer" class="ol-popup-closer" onclick="()=>{$()}"> 关闭 </a>
        <div id="popup-content"></div>
    </div>
    <div id="map" class="map"></div>
    <script src="../library/ol/ol-debug.js"></script>
    <script src="./js/common.js"></script>
    <script type="text/javascript">
        $(function() {
            $("#toggle").click(function() { $("#coordinateBox").toggle() })

            var iconStyle = new ol.style.Style({
                image: new ol.style.Icon({
                    opacity: 0.75,
                    src: "imgs/location.png",
                    cursor: 'pointer'
                }),
            });

            // 提示框
            var container = document.getElementById("popup");
            var content = document.getElementById("popup-content");
            var popupCloser = document.getElementById("popup-closer");
            var overlay = new ol.Overlay({
                //设置弹出框的容器
                element: container,
                //是否自动平移，即假如标记在屏幕边缘，弹出时自动平移地图使弹出框完全可见
                autoPan: true
            });

            // 水平地包裹世界。如果要在-180°和180°经络之间进行矢量编辑才能正常工作，则应将其设置为false。由此产生的几何坐标将超过世界范围。
            var source = new ol.source.Vector({})
            var source2 = new ol.source.Vector({})

            var vector = new ol.layer.Vector({
                source: source,
            });
            var vector2 = new ol.layer.Vector({
                source: source2,
                // 自定义点线面样式
                style: new ol.style.Style({
                    image: new ol.style.Icon({
                        opacity: 0.75,
                        src: "imgs/location.png",
                        cursor: 'pointer'
                    }),
                })
            });

            // add gaode
            var gaodeMapLayer = new ol.layer.Tile({
                source: new ol.source.XYZ({
                    url: 'http://wprd0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&style=7&x={x}&y={y}&z={z}'
                })
            });

            var map = new ol.Map({
                layers: [gaodeMapLayer, vector, vector2],
                view: new ol.View({
                    center: [13404016.389345577, 4314908.465212342],
                    zoom: 4
                }),
                target: 'map'
            })
            // debugger

            var typeSelect = document.getElementById('type');

            var draw; // global so we can remove it later
            function addInteraction() {
                var value = typeSelect.value;
                if (value !== 'None') {
                    // map.removeLayer(vector);
                    console.log(vector);
                    // debugger
                    draw = new ol.interaction.Draw({
                        source: source,
                        type: typeSelect.value
                    });
                    map.addInteraction(draw);
                    // 绘制完成，获取坐标
                    draw.on('drawend', function(event) {
                        let feature = event.feature;
                        // 移除之前的
                        source.clear()
                        // event.feature 就是当前绘制完成的线的Feature
                        var points = JSON.stringify(feature.getGeometry().getCoordinates());
                        $('#coordinateBox>span').html(points)
                        // document.getElementById("submit").onclick=function() { ... }
                        $("#submit").off().click(function() {
                            // 写往后逻辑
                            feature.setId(points)
                            feature.set("name", $("#name").val())
                            feature.set("describe", $("#describe").val())
                            source2.addFeature(event.feature)
                        
                        })
                    });

                    map.on('click', function(e) {
                        // view.setCenter(e.coordinate)
                        //在点击时获取像素区域
                        var pixel = map.getEventPixel(e.originalEvent);
                        map.forEachFeatureAtPixel(pixel, function(feature) {
                            var data = feature.getProperties();
                            var featureId = feature.getId();
                            if (featureId !== undefined) {
                                // var data2 = feature.getCoordinates();
                                //coodinate存放了点击时的坐标信息
                                // alert(data)
                                var coodinate = e.coordinate;
                                //设置弹出框内容，可以HTML自定义
                                var text = "<span style='word-wrap:break-word'>你点击的坐标为：" + coodinate +
                                    "</span style='word-wrap:break-word'>";
                                text += "<span style='word-wrap:break-word'>我的名字是：" + data.name +
                                    "</span style='word-wrap:break-word'>";
                                text += "<span style='word-wrap:break-word'>我的名字是：" + data.describe +
                                    "</span style='word-wrap:break-word'>";
                                content.innerHTML = text;
                                //设置overlay的显示位置
                                overlay.setPosition(coodinate);
                                //显示overlay
                                map.addOverlay(overlay);
                            }
                        });
                    });

                    map.on('pointermove', function(e) {
                        var pixel = map.getEventPixel(e.originalEvent);
                        var hit = map.hasFeatureAtPixel(pixel);
                        if (hit) {
                            map.getTargetElement().style.cursor = 'pointer';
                        } else {
                            map.getTargetElement().style.cursor = '';
                        }
                    });

                    popupCloser.onclick = function() {
                        overlay.setPosition(undefined);
                        popupCloser.blur();
                        return false;
                    };
                }
            }

            /**
             * Handle change event.
             */
            typeSelect.onchange = function() {
                map.removeInteraction(draw);
                addInteraction();
            };
            addInteraction();

        })
    </script>
</body>